/*
 * @Description: 单位选择
 * @Author: Zzt
 * @Date: 2023-02-22 11:27:24
 * @LastEditTime: 2023-02-22 14:22:52
 */
import { fetchAllUnit } from '@/api/units';
import JPModal from '@/components/JPComponents/JPModal';
import { ICommonDialog } from '@/interfaces/global';
import { arrToTree } from '@/utils';
import { Button, Form, Tree } from 'antd';
import { useEffect, useState } from 'react';
import { useAnnouncementMgtContext } from '../../contexts/AnnouncementMgtContext';

interface IEditAnnounce extends ICommonDialog {
  data: any;
}
const UnitSelection = (props: IEditAnnounce) => {
  const { visible, data, onClose } = props;
  const { editAnnounce } = useAnnouncementMgtContext();
  const [treeData, setTreeData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);

  const [form] = Form.useForm();

  // 加载时获取单位列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    fetchAllUnit({}).then((res) => {
      console.log(res);
      const _unitList = res.data;
      const unitTree = arrToTree(_unitList);
      setTreeData(unitTree);
      setCheckedKeys(data.checkedKeys);
    });
  }, []);
  const onFinish = () => {
    editAnnounce({ ...data, checkedKeys, status: 2 });
    // 修改接口
    console.log('单位选择', { ...data, checkedKeys, status: 2 });
    onClose();
  };

  const onCheck = (checkedKeysValue: any) => {
    setCheckedKeys(checkedKeysValue);
  };

  return (
    <JPModal
      title="选择单位"
      visible={visible}
      onCancel={onClose}
      footer={[
        <Button key={'close'} onClick={() => onClose()}>
          取消
        </Button>,
        <Button key={'submit'} type="primary" onClick={() => form.submit()}>
          保存
        </Button>
      ]}
    >
      <Form form={form} onFinish={onFinish}>
        <Form.Item name="unit">
          <Tree
            checkable
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            fieldNames={{ title: 'unitName', key: 'id' }}
            treeData={treeData}
          />
        </Form.Item>
      </Form>
    </JPModal>
  );
};
export default UnitSelection;
